import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

public class Convert {

	/**
	 * 目标目录
	 */
	public static String targetDir = Run.targetDir;

	/**
	 * 目标编码
	 */
	public static String targetEncode = Run.targetEncode;

	public static String srcEncode = Run.srcEncode;

	public static String targetRange = Run.targetRange;

	public static boolean isNeedConvert(File file) {
		if (file.getName().lastIndexOf(".") < 0)
			return false;

		String s = file.getName().substring(file.getName().lastIndexOf("."),
				file.getName().length());
		// System.out.println(s);

		return Run.targetRange.contains(s);
	}

	private static boolean isHtml(File file) {
		if (file.getName().lastIndexOf(".") < 0)
			return false;

		String s = file.getName().substring(file.getName().lastIndexOf("."),
				file.getName().length());
		// System.out.println(s);

		String htmlRange = ".html;.htm;";
		return htmlRange.contains(s);
	}

	static String result="";
	public static void convert() throws FileNotFoundException,
			UnsupportedEncodingException, IOException {
		getAllFileList(targetDir);
		System.out.println("file num:" + filelist.size());
		for (File file : filelist) {
			if (isNeedConvert(file)) {
				System.out.println("转化" + file);
				
				 result+=readFile(file);
//				writeFile(file, readFile(file));

			}

		}
		System.out.println("替换完成");
		
		System.out.println(result);
		
		writeFile(new File(Run.result_file),result);

	}

	/**
	 * 读取文件
	 * 
	 * @param file
	 * @return
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public static String readFile(File file) throws FileNotFoundException,
			IOException {
		String encode = "utf-8";
		encode = new FileCharsetDetector().guestFileEncoding(file);
		System.out.println("原有编码" + encode);
		BufferedReader bufread = null;

		bufread = new BufferedReader(new InputStreamReader(new FileInputStream(
				file), encode));

		String read = null;
		StringBuilder content = new StringBuilder();

		int i = 0;
		boolean isHtml = isHtml(file);
		while ((read = bufread.readLine()) != null&&i<120) {//只读取120行
			i++;
			// 替换 <meta http-equiv="Content-Type"
			// content="text/html; charset=gb2312" />中的gb2312
			String t = read.toLowerCase();
			if (isHtml && i < 20 && t.startsWith("<meta")
					&& t.contains("charset")) {

				read = read.replace(srcEncode, targetEncode);
				read = read.replace(srcEncode.toUpperCase(), targetEncode);
				read = read.replace(srcEncode.toLowerCase(), targetEncode);

			}
			
			String read2=read.replace("\t", "\t").trim();
			if(read2.length() == 0||read2.equals("")||read2.startsWith("//")||read2.startsWith("/*")||read2.startsWith("*")){
				System.out.println("#多余的换行#");
			}else{
				content.append(read).append("\r\n");
			}
			

		}// end of while
		return content.toString();

	}
//
	/**
	 * 写入文件
	 * 
	 * @param file
	 * @param content
	 * @throws FileNotFoundException
	 * @throws UnsupportedEncodingException
	 */
	public static void writeFile(File file, String content)
			throws FileNotFoundException, UnsupportedEncodingException {

		PrintWriter printEdit = null;

		printEdit = new PrintWriter(file, targetEncode);

		printEdit.write(content);
		printEdit.flush();
		printEdit.close();

	}

	private static ArrayList<File> filelist = new ArrayList<File>();

	// public static void main(String[] args) {
	//
	// long a = System.currentTimeMillis();
	// getAllFileList(targetDir);
	// System.out.println(System.currentTimeMillis() - a);
	// }

	/**
	 * 获得所有的目录
	 * 
	 * @param strPath
	 */
	public static void getAllFileList(String strPath) {
		File dir = new File(strPath);
		File[] files = dir.listFiles();

		if (files == null)
			return;
		for (int i = 0; i < files.length; i++) {
			if (files[i].isDirectory()) {
				getAllFileList(files[i].getAbsolutePath());
			} else {
				// String strFileName =
				// files[i].getAbsolutePath().toLowerCase();
				// System.out.println("---" + strFileName);
				// filelist.add(files[i].getAbsolutePath());
				filelist.add(files[i]);
			}
		}
	}
}
